package com.chx.rpc04;

import com.chx.api.UserService;
import com.chx.dto.User;

import java.io.*;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

public class Stub {
    public static UserService getStub() {
        InvocationHandler h = new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Socket socket=new Socket("localhost",8080);
                OutputStream os = socket.getOutputStream();
                ObjectOutputStream oos= new ObjectOutputStream(os);

                oos.writeUTF(method.getName());
                oos.writeObject(method.getParameterTypes());
                oos.writeObject(args);
                oos.flush();

                InputStream is = socket.getInputStream();
                ObjectInputStream ois = new ObjectInputStream(is);

                User user = (User) ois.readObject();

                ois.close();
                oos.close();
                return user;
            }
        };
        Object o = Proxy.newProxyInstance(UserService.class.getClassLoader(), new Class[]{UserService.class}, h);
        return (UserService)o;
    }
}
